package io.hepu.robotize.config;

import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.core.io.support.PropertySourceFactory;
import org.springframework.lang.NonNull;
import org.springframework.lang.Nullable;

import java.io.IOException;
import java.util.Objects;
import java.util.Properties;

public class YamlPropertySourceFactory implements PropertySourceFactory {

    /**
     * Create a {@link PropertySource} that wraps the given resource.
     *
     * @param name     the name of the property source, or {@code null} to use the resource's filename
     * @param resource the resource (potentially encoded) to wrap
     * @return the new {@link PropertySource} (never {@code null})
     * @throws IOException if resource resolution failed
     */
    @Override
    public @NonNull
    PropertySource<?> createPropertySource(@Nullable String name, @NonNull EncodedResource resource)
            throws IOException {
        YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
        factory.setResources(resource.getResource());
        factory.afterPropertiesSet();

        // Retrieve properties from YAML, ensuring the result is not null
        Properties properties = Objects.requireNonNull(factory.getObject(), "Failed to load properties from YAML file");

        // Use the provided name, or the resource's filename if name is null
        String resourceName = (name != null) ? name :
                Objects.requireNonNull(resource.getResource().getFilename(), "Resource must have a filename");

        return new PropertiesPropertySource(resourceName, properties);
    }
}
